﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace WPFTestSolution.Pages.Controls.ItemsControls {
    
    /**
     * https://www.bilibili.com/video/BV1bV411A7Eq?p=58
     * 058-TreeView树控件(: ItemsControl)
     * https://www.wpfsoft.com/2023/09/08/1904.html
     */
    public partial class _58_TreeView_Page : Page {
        public _58_TreeView_Page() {
            InitializeComponent();
            this.Title = "058-TreeView树控件(: ItemsControl)";
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            /**
             * 添加依赖: System.Windows.Forms v4.0.0.0
             * .NETFramework: <Reference Include="System.Windows.Forms" />
             * .NET 8.0     : <UseWindowsForms>true</UseWindowsForms>
             */
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                _TextBox.Text = dialog.SelectedPath;
                LoadTreeView(dialog.SelectedPath);
            }
        }

        
        private void LoadTreeView(string rootPath) {
            // 设置根节点
            TreeViewItem rootNode = new TreeViewItem {
                Header = "根目录"
            };
            // 加载子文件夹和文件
            LoadSubDirectory(rootNode, rootPath);
            // 将根节点添加到TreeView中
            _TreeView.Items.Add(rootNode);
        }
        
        private void LoadSubDirectory(TreeViewItem node, string path) {
            try {
                DirectoryInfo dirInfo = new DirectoryInfo(path);
 
                // 加载子文件夹
                foreach (DirectoryInfo subDirInfo in dirInfo.GetDirectories()) {
                    TreeViewItem subNode = new TreeViewItem();
                    subNode.Header = subDirInfo.Name;
 
                    LoadSubDirectory(subNode, subDirInfo.FullName);
 
                    node.Items.Add(subNode);
                }
 
                // 加载文件
                foreach (FileInfo fileInfo in dirInfo.GetFiles()) {
                    TreeViewItem subNode = new TreeViewItem();
                    subNode.Header = fileInfo.Name;
 
                    node.Items.Add(subNode);
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
        
        private void _TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) {
            // 显示选中节点的Header
            if (_TreeView.SelectedItem is TreeViewItem selectedNode) {
                this.TextBlock.Text = $"选择结果: {selectedNode.Header}";
            }
        }
    }
}